#!/usr/bin/env python
# -*- coding: UTF-8 -*-

'''GUI for http://en.wikipedia.org/wiki/Cellular_automaton#Elementary_cellular_automata'''

import os
import time
import subprocess
import re

from cellular_automata.elementary import ElementaryCellularAutomata
from cellular_automata.cellular_engine.constants import WORLD_TYPE_DEAD_AROUND

print('rule?')
rule = raw_input('> ')

if rule == '':
    print('Defaulting to rule 90!')
    rule = 90
else:
    rule = int(rule)

print('\nHow many cells per row?')
cells_per_row = raw_input('> ')

if cells_per_row == '':
    if os.name == 'nt':
        foo = subprocess.Popen('mode con', stdout=subprocess.PIPE, shell=True).communicate()[0]
        match = re.findall('\n.+\r', foo)[3]
        start_slice = match.rfind(':')

        max_rowwidth = int(match[start_slice + 1:-1])

        cells_per_row = max_rowwidth - 2
        print('\nUsing max width: %i cells per row!' % cells_per_row)
    else:
        print('\Defaulting to 51 cells per row!')
        cells_per_row = 51
else:
    cells_per_row = int(cells_per_row)

print('\nStarting row?')
starting_row = raw_input('> ')

if starting_row == '':
    print('Defaulting to "1"')
    starting_row = '1'

print('\nDelay between rows?')
delay = raw_input('> ')

if delay == '':
    print('Defaulting to 0.05!')
    delay = 0.05
else:
    delay = float(delay)

if __name__ == '__main__':
    ca = ElementaryCellularAutomata(rule, starting_row, cells_per_row,
                                    WORLD_TYPE_DEAD_AROUND)

    while True:
        row = ca.rows[-1]
        row = row.replace('0', ' ')
        row = row.replace('1', u'\u25A0')

        print(row)

        ca.game_loop()
        time.sleep(delay)
